package com.qf.pickname.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.stylesheets.LinkStyle;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/pick")
@Slf4j
public class PicknameController {

    public static final String PICKED_FILE_NAME = "D:\\2301\\picked.txt";
    public static final String ALL_FILE_NAME = "D:\\2301\\2301名单.txt";

    @GetMapping("/reset")
    public String reset() throws IOException {
        // 把 D:\2301\picked.txt 内容清空
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(PICKED_FILE_NAME));
        bufferedWriter.write("");
        bufferedWriter.flush();
        bufferedWriter.close();

        return "重置完毕";
    }

    // 写一个web接口，实现随机点名
    @GetMapping("/name")
    public String pickname(boolean flag) throws Exception {
        log.info("入参为:flag={}",flag);

        //1. 获取所有学生的名单，存放到一个list中
        List<String> nameList = fileToList(ALL_FILE_NAME);
        //2. 根据flag进行不同的处理
        if (flag){
            //如果为true，就是可重复点名
            int index = new Random().nextInt(nameList.size());
            String name = nameList.get(index);
            log.info("中奖的同学为:{}",name);
            return name;
        }else {
            // 如果传入false，则实现不重复点名
            // 获取所有已经点过名的学生的名单list
            List<String> pickednameList = fileToList(PICKED_FILE_NAME);
            // 做减法运算，nameList-pickednameList
            nameList.removeAll(pickednameList);
            if (nameList!=null&&nameList.size()>0){
                int index = new Random().nextInt(nameList.size());
                String name = nameList.get(index);
                log.info("中奖的同学为:{},把中奖同学记录到picked.txt文件中",name);
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(PICKED_FILE_NAME, true));
                bufferedWriter.write(name);
                bufferedWriter.newLine();
                bufferedWriter.flush();
                bufferedWriter.close();
                return name;
            }
            // 都点完了
            return "都点完了!请重置";
        }

    }

    private List<String> fileToList(String file) throws Exception {

        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        ArrayList<String> list = new ArrayList<>();

        String name= null;

        while ( (name=bufferedReader.readLine())!=null ){
            list.add(name);
        }

        bufferedReader.close();
        return list;
    }

}
